package com.wanwu.channel.common.util;

import java.util.Random;

public class RandomUtil {

    private static final Random rand = new Random();

    /**
     * 根据随机数组返回某个区间 比如probability = [20,30,50] 则返回0/1/2，0、1、2的概率分别是20%、30%、50%
     *
     * @param probability
     * @return
     */
    public static int roll(Integer[] probability) {
        int sum = 0;
        for (Integer rd : probability) {
            sum += rd;
        }
        return roll(probability, sum);
    }

    private static int roll(Integer[] probability, int base) {
        int roll = getRandNumber(base);
        for (int i = 0; i < probability.length; i++) {
            if (roll < probability[i]) {
                return i;
            }
            roll -= probability[i];
        }
        return -1;
    }

    public static int getRandNumber(int maxNumber) {
        return rand.nextInt(maxNumber);
    }


    /**
     * 生成lenth个随机数串
     * @param length
     * @return
     */
    public static String randomNStr(int length) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < length;i++) {
            int next = rand.nextInt();
            if(next < 0){
                next = Math.abs(next);
            }
            sb.append(next%10);
        }
        return sb.toString();
    }

}
